package com.CST.service.impl.cb;

import com.CST.common.api.Response;
import com.CST.dto.cb.DateDTO;
import com.CST.entity.cb.JxObjectiveAssessment;
import com.CST.mapper.cst.cb.JxCostMapper;
import com.CST.mapper.cst.cb.JxObjectiveAssessmentMapper;
import com.CST.service.cb.IJxCostService;
import com.CST.service.cb.JxObjectiveAssessmentService;
import com.CST.util.ExcelTransfer;
import com.CST.vo.cb.BudgetAssessmentVO;
import com.CST.vo.cb.JXInComeVO;
import com.CST.vo.cb.JxObjectiveAssessmentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.bind.v2.TODO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author qtx
 * @since 2023-05-24
 */
@Service
public class JxObjectiveAssessmentServiceImpl extends ServiceImpl<JxObjectiveAssessmentMapper, JxObjectiveAssessment> implements JxObjectiveAssessmentService {

    @Autowired
    private JxCostMapper jxCostMapper;
@Autowired
private IJxCostService  iJxCostService;
    private final ExcelTransfer<JxObjectiveAssessment> excelTransfer;
    private final ExcelTransfer<JxObjectiveAssessmentVO> excelTransfer1;

    public JxObjectiveAssessmentServiceImpl(ExcelTransfer<JxObjectiveAssessment> excelTransfer, ExcelTransfer<JxObjectiveAssessmentVO> excelTransfer1) {
        this.excelTransfer = excelTransfer;
        this.excelTransfer1 = excelTransfer1;
    }

    @Override
    public Response modifyJxObjectiveAssessment(JxObjectiveAssessment entity) {

        try {
            LambdaUpdateWrapper<JxObjectiveAssessment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(JxObjectiveAssessment::getYear, entity.getYear())
                    .eq(JxObjectiveAssessment::getDeptCode, entity.getDeptCode());

            boolean update = saveOrUpdate(entity, lambdaUpdateWrapper);
        } catch (Exception e) {
            return Response.error(String.join(":", "添加失败:", e.getMessage()));
        }

        return Response.success("修改成功");
    }

    @Override
    public List<JxObjectiveAssessmentVO> queryByYear(DateDTO dateDTO) throws ExecutionException, InterruptedException {
        int finish  = 0;
        if (dateDTO.getStarMonth()!=null&&dateDTO.getEndMonth()!=null){
            int starMonth = dateDTO.getStarMonth();
            int endMonth = dateDTO.getEndMonth();
            finish =endMonth - starMonth +1;
        }
        //成本+固定资产
        // TODO: 2023/6/30 父级科室的查询sql被我删了 这里记得改
        List<BudgetAssessmentVO> benefitReportForms = iJxCostService.benefitReportForms(dateDTO);
        List<BudgetAssessmentVO> parentInformation=  benefitReportForms.stream().filter(s->s.getIsParent().equals("0")).collect(Collectors.toList());
       //收入
        List<JXInComeVO> jxInComeVOS = jxCostMapper.queryInComeVos(dateDTO);
        LambdaQueryWrapper<JxObjectiveAssessment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(JxObjectiveAssessment::getYear, dateDTO.getStarYear());
        List<JxObjectiveAssessment> jxObjectiveAssessments = baseMapper.selectList(lambdaQueryWrapper);
        List<JxObjectiveAssessment> jxObjectiveAssessments1 = baseMapper.selectDeptCode();
        List<JxObjectiveAssessmentVO> jxObjectiveAssessmentVOList = new ArrayList<>();
        for (JxObjectiveAssessment jxObjectiveAssessment : jxObjectiveAssessments1) {
            JxObjectiveAssessmentVO jxObjectiveAssessmentVO = new JxObjectiveAssessmentVO();
            jxObjectiveAssessmentVO.setDeptCode(jxObjectiveAssessment.getDeptCode());
            jxObjectiveAssessmentVO.setDeptName(jxObjectiveAssessment.getDeptName());
            JxObjectiveAssessment jxObjectiveAssessment1 = jxObjectiveAssessments.stream().filter(t -> t.getDeptCode().equals(jxObjectiveAssessment.getDeptCode())).findFirst().orElse(null);
            BudgetAssessmentVO budgetAssessmentVO = parentInformation.stream().filter(t -> t.getDeptCode().equals(jxObjectiveAssessment.getDeptCode())).findFirst().orElse(null);
            JXInComeVO jxInComeVO = jxInComeVOS.stream().filter(t -> t.getPDeptCode().equals(jxObjectiveAssessment.getDeptCode())).findFirst().orElse(null);
          //万元固定资产服务量（折算成3个月）
            if (budgetAssessmentVO == null || budgetAssessmentVO.getOriginalValue().compareTo(BigDecimal.ZERO) == 0 || jxInComeVO == null || jxInComeVO.getTOTAL().compareTo(BigDecimal.ZERO) == 0) {
                jxObjectiveAssessmentVO.setAssetsAmount(BigDecimal.ZERO);
            } else {
                //计算一个季度
                Integer num = (dateDTO.getEndMonth() - dateDTO.getStarMonth() + 1) ;
                BigDecimal multiply = jxInComeVO.getTOTAL().divide(BigDecimal.valueOf(num), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(3)).divide(budgetAssessmentVO.getOriginalValue(), 4,RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(10000));
                jxObjectiveAssessmentVO.setAssetsAmount(multiply);
            }

            if (budgetAssessmentVO == null || budgetAssessmentVO.getSummation().compareTo(BigDecimal.ZERO) == 0 || jxInComeVO == null || jxInComeVO.getTOTAL().compareTo(BigDecimal.ZERO) == 0) {
                jxObjectiveAssessmentVO.setCostRatio(BigDecimal.ZERO);
            } else {
                jxObjectiveAssessmentVO.setCostRatio(budgetAssessmentVO.getSummation().divide(jxInComeVO.getTOTAL(),4,RoundingMode.HALF_UP));
            }

            if (jxObjectiveAssessment1 != null) {
                jxObjectiveAssessmentVO.setYearRatio(jxObjectiveAssessment1.getYearRatio());
                jxObjectiveAssessmentVO.setYearAmount(jxObjectiveAssessment1.getYearAmount());
                jxObjectiveAssessmentVO.setWeightRatio(jxObjectiveAssessment1.getWeightRatio());
                jxObjectiveAssessmentVO.setWeightAmount(jxObjectiveAssessment1.getWeightAmount());
                jxObjectiveAssessmentVO.setDirectorWeight(jxObjectiveAssessment1.getDirectorWeight());
            } else {
                jxObjectiveAssessmentVO.setYearRatio(BigDecimal.ZERO);
                jxObjectiveAssessmentVO.setYearAmount(BigDecimal.ZERO);
                jxObjectiveAssessmentVO.setWeightRatio(BigDecimal.ZERO);
                jxObjectiveAssessmentVO.setWeightAmount(BigDecimal.ZERO);
                jxObjectiveAssessmentVO.setDirectorWeight(BigDecimal.ZERO);
            }
            if (jxObjectiveAssessmentVO.getCostRatio().compareTo(BigDecimal.ZERO) == 0) {
                jxObjectiveAssessmentVO.setCostRate(BigDecimal.ZERO);
            } else {
                jxObjectiveAssessmentVO.setCostRate(jxObjectiveAssessmentVO.getYearRatio().divide(jxObjectiveAssessmentVO.getCostRatio(),4,RoundingMode.HALF_UP));
            }


            if (jxObjectiveAssessmentVO.getYearAmount().compareTo(BigDecimal.ZERO) == 0) {
                jxObjectiveAssessmentVO.setJsAmount(BigDecimal.ZERO);
            } else {

                jxObjectiveAssessmentVO.setJsAmount(jxObjectiveAssessmentVO.getAssetsAmount().divide(jxObjectiveAssessmentVO.getYearAmount(),4,RoundingMode.HALF_UP));
            }
            if (jxObjectiveAssessmentVO.getCostRate().compareTo(BigDecimal.ONE) > 0) {
                jxObjectiveAssessmentVO.setTestCostRate(jxObjectiveAssessmentVO.getWeightRatio());
            } else {
                if (jxObjectiveAssessmentVO.getCostRate().compareTo(BigDecimal.ONE) == 0||jxObjectiveAssessmentVO.getWeightRatio().compareTo(BigDecimal.ONE) == 0){
                    jxObjectiveAssessmentVO.setTestCostRate(BigDecimal.ZERO);
                }else {
                    BigDecimal testCostRate = jxObjectiveAssessmentVO.getWeightRatio().multiply(jxObjectiveAssessmentVO.getCostRate()).setScale(4, RoundingMode.HALF_UP);
                    jxObjectiveAssessmentVO.setTestCostRate(testCostRate);
                }
            }

            if (jxObjectiveAssessmentVO.getJsAmount().compareTo(BigDecimal.ONE) > 0) {
                jxObjectiveAssessmentVO.setTestAmount(jxObjectiveAssessmentVO.getWeightAmount());
            } else {
                jxObjectiveAssessmentVO.setTestAmount(jxObjectiveAssessmentVO.getWeightAmount().multiply(jxObjectiveAssessmentVO.getJsAmount()));
            }
            if (jxObjectiveAssessmentVO.getWeightAmount().add(jxObjectiveAssessmentVO.getWeightRatio()).compareTo(BigDecimal.ZERO) == 0) {
                jxObjectiveAssessmentVO.setDirectorScore(BigDecimal.ZERO);
            } else {
                BigDecimal add = jxObjectiveAssessmentVO.getWeightAmount().add(jxObjectiveAssessmentVO.getWeightRatio());
                BigDecimal add1 = jxObjectiveAssessmentVO.getTestCostRate().add(jxObjectiveAssessmentVO.getTestAmount());
                if (add.compareTo(BigDecimal.ZERO)==0){
                    jxObjectiveAssessmentVO.setDirectorScore(BigDecimal.ZERO);
                }else {
                    BigDecimal directorScore = add1.divide(add, 4, RoundingMode.HALF_UP).multiply(jxObjectiveAssessmentVO.getDirectorWeight()).setScale(4, RoundingMode.HALF_UP);
                    jxObjectiveAssessmentVO.setDirectorScore(directorScore);}
                }

            jxObjectiveAssessmentVOList.add(jxObjectiveAssessmentVO);
        }

        return jxObjectiveAssessmentVOList;
    }

    @Override
    @Transactional
    public void importExcelJxObjectiveAssessment(MultipartFile file, Integer year) {
        baseMapper.delete(new QueryWrapper<JxObjectiveAssessment>().eq("YEAR", year));
        excelTransfer.importExcel(file, this, JxObjectiveAssessment.class);
    }

    @Override
    public void exportExcelJxObjectiveAssessment(HttpServletResponse response,DateDTO dateDTO) throws ExecutionException, InterruptedException {
        List<JxObjectiveAssessmentVO> jxObjectiveAssessmentVOList = this.queryByYear(dateDTO);
        excelTransfer1.exportExcel(response, jxObjectiveAssessmentVOList, "绩效考核得分表", "sheet", JxObjectiveAssessmentVO.class);

    }

    @Override
    public void exportExcelJxObjectiveAssessmentDemo(HttpServletResponse response) {
        excelTransfer.exportExcel(response, baseMapper.selectDeptCode(), "考核权重", "sheet", JxObjectiveAssessment.class);
    }
}
